package com.jxd.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class FileController {
    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("upload") MultipartFile multipartFile, HttpServletRequest request) {
        /*创建一个目录，用于存放上传的文件*/
        String savePath = "C:\\Users\\22446\\Desktop\\t";
        File file = new File(savePath);
        //file不存在或者不是一个目录
        if (!file.exists() || !file.isDirectory()) {
            file.mkdir();
        }
        //获取源文件名 xxx.png
        String oldName = multipartFile.getOriginalFilename();
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));

        //根据savePath和newName生成一个文件对象
        File saveFile = new File(savePath, newName);
        try {
            //将springmvc接收到的文件对象转换为普通的文件对象
            //转换的过程即保存的过程
            multipartFile.transferTo(saveFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("23ffe");
        //返回文件保存路径及文件名，以便删除时使用
        return "files/" + newName;
    }
}
